package solutions;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.pi4.locutil.GeoPosition;

public class ScoreNN {

	public static void main(String[] args) throws IOException {
		if (args.length == 0) {
			args = new String[] { "FingerPrintingNN.txt", "ModelNN.txt",
					"ModelKNN.txt", "FingerPrintingKNN.txt" };
			//args = new String[] { "FingerPrintingKNN.txt" };
			System.out.print("Need a file to read, defaults to following files: ");
			for (String filename : args) {
				System.out.print("\t " + filename+"\n");
			}
		}
		for (String filename : args) {
			List<Double> distances = new ArrayList<Double>();
			calculateDistances(filename, distances);
			writeErrorDistribution(distances, filename);
		}

	}

	private static void writeErrorDistribution(List<Double> distances,
			String filename) throws IOException {
		BufferedWriter writer = new BufferedWriter(new FileWriter("ScoreNN_"
				+ filename));

		Collections.sort(distances);
		
		int numberOfElements = distances.size();
		float probability = 0.0f;
		float interval = 0.10f;
		float currPlace = 0.0f;
		int numOfOccurences = 0;
		//the data can be plotted whit gnuplot :
		//plot "filename" using 1:2 with lines
		writer.write("#Error distance \t Probability\n");
		for(Double d : distances) {
			numOfOccurences++;
			if(d > currPlace) {
				currPlace += interval;
				probability = (float)numOfOccurences/numberOfElements;
				writer.write(d+"\t"+probability+"\n");
				//System.out.println(d+"\t"+probability);
			}
		}
		writer.close();
	}

	private static void calculateDistances(String filename,
			List<Double> distances) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(new File(
				filename)));
		// Skip first line with info about order
		reader.readLine();
		String s = null;

		while ((s = reader.readLine()) != null) {
			s = s.trim();
			String[] splitting = s.split("[,;\t()]");

			double estX = Double.parseDouble(splitting[1]);
			double estY = Double.parseDouble(splitting[2]);
			double estZ = Double.parseDouble(splitting[3]);

			double realX = Double.parseDouble(splitting[8]);
			double realY = Double.parseDouble(splitting[9]);
			double reaZ = Double.parseDouble(splitting[10]);

			distances.add(PositionUtils.getDistance(new GeoPosition(estX, estY,
					estZ), new GeoPosition(realX, realY, reaZ)));
		}
	}
}
